//
//  ANloginViewController.m
//  Ants
//
//  Created by ZHM on 16/4/11.
//  Copyright © 2016年 ZHM. All rights reserved.
//

#import "ANloginViewController.h"

#define ANLoginOKNote @"loginOKNote"


@interface ANloginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *userPassWord;



@end

@implementation ANloginViewController

- (instancetype)init {
    if (self = [super init]){
    UIStoryboard *storyboard=[UIStoryboard storyboardWithName:@"login" bundle:nil];
    self = [storyboard instantiateInitialViewController];
    self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"登录账号";
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)loginClickBtn:(id)sender {
    if (self.userPassWord.text.length == 0 || self.userName.text.length == 0) {
        NSLog(@"输入用户名密码不正确!");
        return;
    }
    //登录
    [sharedWebService loginWithAccount:self.userName.text passWord:self.userPassWord.text completion:^(BmobUser *user, BOOL succeeded, NSError *error) {
        if (succeeded) {
            NSLog(@"用户:%@登录成功!",user.username);
            [self upUserData];
            [SVProgressHUD showWithStatus:@"登录中..."];
        } else {
            NSLog(@"登录失败:%@",error);
        }
    }];
}
- (void)upUserData {
    [sharedWebService fetchUserWithBmobCompletion:^(ANBmobUser *user, NSError *error) {
        if (!error) {
            [SVProgressHUD dismiss];
            //跳转界面
            [self.navigationController popToRootViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:ANLoginOKNote object:nil];
            [sharedWebService fetchUserBasicInfoWithCompletion:nil];
        }
    }];
    
}
- (IBAction)registeredClick:(id)sender {
    [sharedWebService registeredWithName:self.userName.text passWord:self.userPassWord.text completion:^(BmobUser *user, BOOL succeeded, NSError *error) {
        if (succeeded) {
            NSLog(@"新账号注册成功!!");
            //注册成功-登录
            [sharedWebService loginWithAccount:user.username passWord:user.password completion:^(BmobUser *user, BOOL succeeded, NSError *error) {
                NSLog(@"新账号登录成功!!");
                //跳转界面
                [self.navigationController popToRootViewControllerAnimated:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:ANLoginOKNote object:nil];
            }];
        } else {
            NSLog(@"注册失败:%@!!",error);
        }
    }];
}

- (void)dealloc {
    NSLog(@"%s",__func__);
}


@end
